<?php
namespace control;
// 消息提醒设置
class reminderSettingClass extends adIndexClass
{
    private const page = 'reminderSetting';
    private const table = 'reminder_settings';
    private const title = '消息提醒设置';

    /*编码入口页*/
    public function home(): string
    {
        $type = $this->get('type') ?: '行政';
        $search = '<i class="container-left-search-ico"></i>' . text(["name" => 'name', 'title' => "分类", 'class' => 'container-left-search', 'keyup' => 'search_left']);
        $space = space;
        $all = $this->getPowerAll();
        //返回
        $rightHtml = $this->homeRight();
        $html = <<<EOT
        <div class="container-main">
            <div class="container-left left" id="container-left">
                $search $space $all
            </div>
            <div class="container-right left" id="container-detail">
				$rightHtml
            </div>
        </div>
<script>
function search_left(e){
    containerLeftSearch(e,'{$this->get('cla')}')
}
function replaceRightDetail(obj, cla = '{$this->get('cla')}') {
     let api, id = $(obj).attr('data-id')
    if (id.length > 0) {
        let that = $(obj).parent('ul')
        const two = that.attr('pid');
        const one = that.parent('ul').attr('pid');
        // ulScal(obj, id)
        $('#container-left').find('li').removeClass('active')
        $(obj).addClass('active')
        api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson'
        $.post(api, {
            menuOne:one,
            menuTwo: two,
            menuThree: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}
 function cancelPage(id){
    if (id){
       let obj =  $("[data-id='"+id+"']");
        replaceRightDetail(obj,'reminderSetting'); 
    }
}
 $(function (){
     cancelPage('{$type}')
 })
</script>
<style>
.container-left{height: calc(100% - 90px);position: fixed !important;min-height: unset;overflow-y: auto;overflow-x: hidden;}
.container-right{height: calc(100% - 90px);margin-left: 18%;width: 80%}
</style>
EOT;
        //返回
        return $this->homeFun($html);
    }

    public function homeRight(): string
    {
        // 搜索
        $html = hidden(['name' => 'menuThree', 'value' => $this->post('menuThree')]);
        //生成查询表单
        $html .=
            text(array('name' => 'id', 'title' => '消息ID')) .
            select(["name" => "type", 'option' => ['提醒消息', '预警消息'], 'title' => '类型']) .
            text(array('name' => 'name', 'title' => '对象')) .
            text(array('name' => 'conditions', 'title' => '发送条件'));
        return $this->search($html, otherButton: '');
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $json['html'] = $this->getPowerAll();
        return json_encode($json, 320);
    }

    /**
     * 获取数据
     *
     * @return array
     */
    private function orginalData(): array
    {
        return [
            '行政',
            '销售',
            '采购',
            '委外',
            '物流',
            '库存',
            '核算',
            '生产',
            '质量',
            '往来账/出纳',
            '总账',
        ];
    }

    public function getPowerAll(array $local = [], string $pid = ''): string
    {
        $result = $local ?: $this->orginalData();
        $style = empty($pid) ? 'pid=0' : ' class="child-node"';
        $temp = "<ul $style $pid>";
        // 角标
        $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
        $lastone = lastone;
        foreach ($result as $key => $value) {
            // 判断下级是否存在
            $pid = "pid=$value";
            if (is_array($value)) {
                $temp .= "<li data-id='$key' onclick=\"replaceRightDetail(this)\">$arrow $key</li>";
                $temp .= $this->getPowerAll($value, $pid);
            } else {
                $temp .= "<li data-id='$value' onclick=\"replaceRightDetail(this)\">$lastone $value</li>";
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 异步加载
     */
    public function homeRightJson(): string
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

    public function homeRightJsonSearch(): string
    {
        return $this->homeSearch();
    }


    /*列表页-查询结果*/
    public function homeSearch(): bool|string
    {
        $menuThree = $this->post('menuThree');
        $and = " and classify = '$menuThree'";
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//对象
            "conditions" => $this->post('conditions'),//条件
        );
        //全等查询数组
        $equal = array(
            "id" => $this->post('id'),//ID
            "type" => $this->post('type'),//类型
        );
        //排序
        $orderBy = $this->orderBy(array(
            "search" => $this->post('orderBy')??null,
            "default" => "更新时间降序",
            "array" => array(
                "time" => array("desc" => "更新时间降序", "site" => ''),
            ),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取表头
        $tr[] = array('', "消息ID", "类型", "对象", '接收人', "发送条件", "条件参数ID", "条件与阈值", "排序号", "更新时间");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => self::title . "详情", "click" => "layer('" . self::page . "','edit',{id:'".$array['id']."'})"),
            );
            $tr[] = array($this->dominate($dominate), $array['id'], $array['type'], $array['name'], checkPlanClass::showSelectorText($array['selector']), $array['conditions'], $array['field_name'], $array['threshold'], $array['list'], $array['updateTime']);
        }
        //返回
        $json['html'] = $page['hint'] ."<form name='trainRecordForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $html = $this->layerEdit(array("table" => array(
            array(
                "消息类型：" => $info['type'],
            ),
            array(
                "消息对象：" => $info['name'],
            ),
            array(
                must."接收人：" => componentClass::staffSelector($info['selector']),
            ),
            array(
                "发送条件：" => $info['conditions']
            ),
            array(
                "条件阈值：" => text(array('name' => 'threshold', 'class' => 'text', 'value' => $info['threshold'])),
            ),
        )));
        //返回
        return $this->layer(array("title" => "编辑",'winFix'=>true, "height" => 470, "width" => 900, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'selector'       => $this->post('staff')[0]??'',//员工选择器
            'threshold' => $this->post('threshold')
        ];
        $field['member'] = implode(',',componentClass::returnStaffId($field['selector']));
        $annotation = [
            'selector' => '接收人',
        ];
        $rules = [
            'selector' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $json['warn'] = "对应消息不存在";
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }

}
